package demolist;

public class MySingleList {
    public class ListNode{
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;
    public void createList() {
        ListNode node1 = new ListNode(12);
        ListNode node2 = new ListNode(23);
        ListNode node3 = new ListNode(34);
        ListNode node4 = new ListNode(45);
        ListNode node5 = new ListNode(56);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        head = node1;

    }
    public int size(){
        ListNode cur=head;
        int count=0;
        while(cur!=null){
            count++;
            cur=cur.next;
        }
        return count;
    }
    public void show(){
        ListNode cur=head;
        while(cur!=null){
            System.out.print(cur.val+" ");
            cur=cur.next;
        }
        System.out.println();
    }
    public boolean contains(int key){
        ListNode cur=head;
        while(cur!=null){
            if(cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }
    public void firstAdd(int data) {
    ListNode node=new ListNode(data);
    node.next=head;
    head=node;
    }
    public void lastAdd(int data){
        ListNode  node=new ListNode(data);
        ListNode cur=head;
        if(head==null){
            head=node;
        }else{
            while(cur.next!=null){
                cur=cur.next;
            }
            cur.next=node;
        }
    }
    public void addIndex(int index,int val) throws IndexExpection {
       if(index<0||index>size()){
           throw new IndexExpection("index位置不合法");
       }
        ListNode node=new ListNode(val);
        ListNode cur=head;
        if(index==0){
            firstAdd(val);
        }else{
            for (int i = 0; i < index-1; i++) {
                cur=cur.next;
            }
            node.next=cur.next;
            cur.next=node;
        }
    }
    public ListNode findMiddleNode(){
        int len=size();
        ListNode cur=head;
        for (int i = 0; i < len/2; i++) {
            cur=cur.next;
        }
        return cur;
    }

}
